//
//  ReaderViewController.m
//  FastPdfKit
//
//  Created by Gianluca Orsini on 28/02/11.
//  Copyright 2010 MobFarm S.r.l. All rights reserved.
//

#import "ReaderViewController.h"
#import "OutlineViewController.h"
#import "MFDocumentManager.h"
#import "SearchViewController.h"
#import "TextDisplayViewController.h"
#import "SearchManager.h"
#import "MiniSearchView.h"
#import "mfprofile.h"
#import "WebBrowser.h"
#import "AudioViewController.h"
#import "MFAudioPlayerViewImpl.h"

#define FPK_REUSABLE_VIEW_NONE 0
#define FPK_REUSABLE_VIEW_SEARCH 1
#define FPK_REUSABLE_VIEW_TEXT 2
#define FPK_REUSABLE_VIEW_OUTLINE 3
#define FPK_REUSABLE_VIEW_BOOKMARK 4

static const NSUInteger FPKReusableViewNone = FPK_REUSABLE_VIEW_NONE;
static const NSUInteger FPKReusableViewSearch = FPK_REUSABLE_VIEW_SEARCH;
static const NSUInteger FPKReusableViewText = FPK_REUSABLE_VIEW_TEXT;
static const NSUInteger FPKReusableViewOutline = FPK_REUSABLE_VIEW_OUTLINE;
static const NSUInteger FPKReusableViewBookmarks = FPK_REUSABLE_VIEW_BOOKMARK;
static NSString *cellId = @"Id";

#define FPK_SEARCH_VIEW_MODE_MINI 0
#define FPK_SEARCH_VIEW_MODE_FULL 1

#define Width(s) [[UIScreen.mainScreen] bounds].size.width / 750 * s
#define Height(s) [[UIScreen mainScreen] bounds].size.height / 1334 * s

#define kH  [UIScreen mainScreen].bounds.size.height/ 667.00
#define kW  [UIScreen mainScreen].bounds.size.width / 375.00
#define SCREEN_WIDTH                    ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT                   ([UIScreen mainScreen].bounds.size.height)
static const NSUInteger FPKSearchViewModeMini = FPK_SEARCH_VIEW_MODE_MINI;
static const NSUInteger FPKSearchViewModeFull = FPK_SEARCH_VIEW_MODE_FULL;

#define PAGE_NUM_LABEL_TEXT(x,y) [NSString stringWithFormat:@" %lu / %lu",(x),(y)]
#define PAGE_NUM_LABEL_TEXT_PHONE(x,y) [NSString stringWithFormat:@"%lu / %lu",(x),(y)]

@interface ReaderViewController() <UIPopoverPresentationControllerDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, readwrite) NSUInteger currentReusableView;
@property (nonatomic, readwrite) NSUInteger currentSearchViewMode;
@property (nonatomic,strong)UILabel * pagelabel ;
/* ** 存放缩略图的数组  ** */
@property (nonatomic,strong)NSMutableArray *thumbnailArray;
/* **   ** */
@property (nonatomic,strong)UITableView *thumbnailView;
@property (nonatomic,strong)UIImageView *imageView;
/* ** <#name#>  ** */
@property (nonatomic,strong)UIView *borderview;
@property (nonatomic,strong)UIView *layerview;
@property (nonatomic, readwrite) BOOL thumbsViewVisible;
@property (nonatomic, readwrite) BOOL waitingForTextInput;
@property (nonatomic, readwrite) BOOL pdfOpen;
@property (nonatomic, readwrite) BOOL willFollowLink;
@property (nonatomic, readwrite) BOOL hudHidden;

/* ** <#name#>  ** */
@property (nonatomic,assign)int thumbsPages;
@end

@implementation ReaderViewController
#pragma mark - UIViewController

/**
 * 加载工具栏图标.
 */
-(void)loadResources {
    
    NSBundle * bundle = [NSBundle bundleForClass:[self class]];
    self.imgDismiss = [UIImage imageNamed:@"Reader/X" inBundle:bundle compatibleWithTraitCollection:nil];
    self.imgSearch = [UIImage imageNamed:@"Reader/search" inBundle:bundle compatibleWithTraitCollection:nil];
}

/**
 * toolbar 工具栏
 */
-(void)prepareToolbar {
    
    NSMutableArray * items = [[NSMutableArray alloc]init];//工具栏item数组
    
    self.searchBarButtonItem = [[UIBarButtonItem alloc]initWithImage:self.imgSearch style:UIBarButtonItemStylePlain target:self action:@selector(actionSearch:)];
    [items addObject:self.searchBarButtonItem];
   
    // Space.
    [items addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]];
    
    // 页码
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 170, 23)];
    
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.shadowColor = [UIColor whiteColor];
    label.shadowOffset = CGSizeMake(0, 1);
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    
    NSString * labelText = [self pageLabelString];
    label.text = self.titleText;
    self.pageNumLabel = label;
    
    self.numberOfPageTitleBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:label];;
    [items addObject:self.numberOfPageTitleBarButtonItem];
    
    // Space.
    
    [items addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]];
    
    
    // fanhui.
    self.dismissBarButtonItem = [[UIBarButtonItem alloc]initWithImage:self.imgDismiss style:UIBarButtonItemStylePlain target:self action:@selector(actionDismiss:)];
    [items addObject:self.dismissBarButtonItem];
 
    
    UIToolbar * toolbar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    toolbar.frame = CGRectMake(0, -self.toolbarHeight, self.view.bounds.size.width, self.toolbarHeight);
    toolbar.hidden = YES;
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [toolbar setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin];
    [toolbar setItems:items animated:NO];
    toolbar.delegate = self;
    
    [self.view addSubview:toolbar];
    
    self.rollawayToolbar = toolbar;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.pdfOpen = YES;
    self.hudHidden = YES;
    self.currentReusableView = FPKReusableViewNone;
    self.multimediaVisible = NO;
    self.toolbarHeight = 44.0;
    
    self.view.backgroundColor = [UIColor darkGrayColor];

    //初始化toolbar图片
    [self loadResources];
    //设置toolBae
    [self prepareToolbar];
    //初始化页码
    [self upDataPage];
    //初始化缩略图
    [self loadThumbnail];
    //初始化缩略图数组
    self.thumbnailArray = [[NSMutableArray alloc]init];
    //边框
    [self loadBorderView];
    //将pdf转换成缩略图
    [self createJPGsFromPDF];
}

-(void)loadBorderView
{
    self.layerview = [[UIView alloc]initWithFrame:CGRectMake(0, 64, 200, 110)];
    self.layerview.layer.borderWidth = 2;
    self.layerview.hidden = YES;
    self.layerview.layer.borderColor = [UIColor greenColor].CGColor;
//    [self.view addSubview:self.layerview];
    
}
-(void)loadThumbnail
{
    self.thumbnailView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 200, self.view.bounds.size.height)];
    self.thumbnailView.backgroundColor = [UIColor colorWithRed:217.0/255 green:217.0/255 blue:217.0/255 alpha:1];
    self.thumbnailView.hidden = YES;
    self.thumbnailView.delegate =self;
    self.thumbnailView.dataSource = self;
    self.thumbnailView.contentInset = UIEdgeInsetsMake(0, 0, 110*kW, 0);
    CGFloat contentHeight = self.view.bounds.size.height;
    self.thumbnailView.contentSize = CGSizeMake(0, contentHeight);
    [self.view addSubview:self.thumbnailView];
}
-(void) createJPGsFromPDF
{
    NSString *docPath = [[NSBundle mainBundle]pathForResource:@"web学习" ofType:@"pdf"];
    NSURL *fromPDFURL = [NSURL fileURLWithPath:docPath];
    CGPDFDocumentRef fromPDFDoc = CGPDFDocumentCreateWithURL((CFURLRef) fromPDFURL);
    // Get Total Pages
    self.thumbsPages = CGPDFDocumentGetNumberOfPages(fromPDFDoc);

    int i = 1;
    for (i = 1; i <= self.thumbsPages; i++) {
        CGPDFPageRef pageRef = CGPDFDocumentGetPage(fromPDFDoc, i);
        CGPDFPageRetain(pageRef);
        
        // determine the size of the PDF page
        CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFMediaBox);
        
        // renders its content.
        UIGraphicsBeginImageContext(pageRect.size);
        
        CGContextRef imgContext = UIGraphicsGetCurrentContext();
        CGContextSaveGState(imgContext);
        CGContextTranslateCTM(imgContext, 0.0, pageRect.size.height);
        CGContextScaleCTM(imgContext, 1.0, -1.0);
        CGContextSetInterpolationQuality(imgContext, kCGInterpolationDefault);
        CGContextSetRenderingIntent(imgContext, kCGRenderingIntentDefault);
        CGContextDrawPDFPage(imgContext, pageRef);
        CGContextRestoreGState(imgContext);
        
        //PDF Page to image
        UIImage *tempImage = UIGraphicsGetImageFromCurrentImageContext();
        [self.thumbnailArray addObject:tempImage];
        UIGraphicsEndImageContext();
        //Release current source page
        CGPDFPageRelease(pageRef);
     // 存储 IMG
//        NSString *imgname = [NSString stringWithFormat:@"fromPDFName_%d.jpg", i];
//        NSString *imgPath = [folderPath stringByAppendingPathComponent:imgname];
//        [UIImageJPEGRepresentation(tempImage, 1.0) writeToFile:imgPath atomically:YES];
        
    }
    
    CGPDFDocumentRelease(fromPDFDoc);
    
}
-(void)upDataPage
{
    //页码数
    self.pagelabel = [[UILabel alloc] initWithFrame:CGRectMake((self.view.bounds.size.width - 170)/2, self.view.bounds.size.height - 23 - 20, 170, 23)];
    
    self.pagelabel.textAlignment = NSTextAlignmentCenter;
    self.pagelabel.backgroundColor = [UIColor colorWithRed:237.0/255 green:243.0/255 blue:247.0/255 alpha:1];
    self.pagelabel.shadowColor = [UIColor whiteColor];
    self.pagelabel.shadowOffset = CGSizeMake(0, 1);
    self.pagelabel.textColor = [UIColor blackColor];
    self.pagelabel.font = [UIFont boldSystemFontOfSize:20.0];
    NSString * labelText = [self pageLabelString];
    self.pagelabel.text = labelText;
    [self.view addSubview:self.pagelabel];
    
    //当前页数绿色的边框
    self.borderview = [[UIView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width/2 - 30, self.view.bounds.size.height - 10 -73, 60, 83)];
    self.borderview.backgroundColor = [UIColor clearColor];
    self.borderview.hidden = YES;
    self.borderview.layer.borderColor = [UIColor greenColor].CGColor;
    self.borderview.layer.borderWidth = 2;
    [self.view addSubview:self.borderview];
    
}
-(NSString *)pageLabelTitleForPage:(NSUInteger)page {
    if(self.pageLabelFormat) {
        return [NSString stringWithFormat:self.pageLabelFormat, page, [[self document] numberOfPages]];
        
    } else if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        
        return PAGE_NUM_LABEL_TEXT((unsigned long)page,(unsigned long)[[self document]numberOfPages]);
    }
    else {
        
        return PAGE_NUM_LABEL_TEXT_PHONE((unsigned long)page,(unsigned long)[[self document]numberOfPages]);
    }
}

-(NSString *)pageLabelString {
    
    return [self pageLabelTitleForPage:[self page]];
}

/**
 * 页面和总页数
 */
-(void)updatePageNumberLabel {
    NSString *labelTitle = [self pageLabelString];
//    self.pageNumLabel.text = labelTitle;
}

-(void)updatePageNumberLabelWithPage:(NSUInteger)page {
    
    NSString *labelTitle = [self pageLabelTitleForPage:page];
//    self.pageNumLabel.text = labelTitle;
}

-(void)showToolbar {
    ReaderViewController * __weak this = self;
    [UIView animateWithDuration:.25f
                          delay:.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         this.rollawayToolbar.hidden = NO;
                         [this setNeedsStatusBarAppearanceUpdate];
                         this.rollawayToolbar.frame = CGRectMake(0, self.topLayoutGuide.length, this.rollawayToolbar.frame.size.width, this.rollawayToolbar.frame.size.height);
                     }
                     completion:^(BOOL finished) {
                         
                     }
     ];
}

-(void)showThumbnaiView
{
    ReaderViewController * __weak this = self;
    [UIView animateWithDuration:.25f
                          delay:.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         this.thumbnailView.hidden = NO;
                         this.layerview.hidden = NO;
                         this.thumbnailView.frame = CGRectMake(0, 64, 200, self.view.bounds.size.height);
                     }
                     completion:^(BOOL finished) {
                         
                     }
     ];
}
-(void)hideThumbnaiView
{
    ReaderViewController * __weak this = self;
    [UIView animateWithDuration:.25f
                          delay:.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                        
                         this.thumbnailView.frame = CGRectMake(0, 64, 0, self.view.bounds.size.height);
                     }
                     completion:^(BOOL finished) {
                          this.thumbnailView.hidden = YES;
                             this.layerview.hidden = YES;
                     }
     ];
}
/**
 * This method will hide the toolbar.
 */
-(void)hideToolbar {
    ReaderViewController * __weak this = self;
    [UIView animateWithDuration:.25f
                          delay:.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [this.rollawayToolbar setFrame:CGRectMake(0, -this.toolbarHeight, this.rollawayToolbar.frame.size.width, this.rollawayToolbar.frame.size.height)];
                     }
                     completion:^(BOOL finished){
                         this.rollawayToolbar.hidden = YES;
                         [this setNeedsStatusBarAppearanceUpdate];
                     }];
}

-(id)initWithDocumentManager:(MFDocumentManager *)aDocumentManager {
    
    self = [super initWithDocumentManager:aDocumentManager];
    if(self) {
        
        self.popoverContentSize = CGSizeMake(372, 650);
        
        [self setDocumentDelegate:self];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleSearchUpdateNotification:)
                                                     name:kNotificationSearchResultAvailable
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleSearchGotCancelledNotification:)
                                                     name:kNotificationSearchGotCancelled
                                                   object:nil];
    }
    
    return self;
}

-(id)initWithDocumentManager:(MFDocumentManager *)aDocumentManager count:(NSUInteger)count {
    self = [super initWithDocumentManager:aDocumentManager count:count];
    if(self) {
        
        self.popoverContentSize = CGSizeMake(372, 650);
        
        [self setDocumentDelegate:self];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleSearchUpdateNotification:)
                                                     name:kNotificationSearchResultAvailable
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleSearchGotCancelledNotification:)
                                                     name:kNotificationSearchGotCancelled
                                                   object:nil];
    }
    
    return self;
}

-(UIPopoverController *)prepareReusablePopoverControllerWithController:(UIViewController *)controller {

    if(!self.reusablePopover) {
        
        UIPopoverController * popoverController = [[UIPopoverController alloc]initWithContentViewController:controller];
        popoverController.delegate = self;
        self.reusablePopover = popoverController;
        self.reusablePopover.delegate = self;
        
    } else {
        
        [self.reusablePopover setContentViewController:controller animated:YES];
    }

    return self.reusablePopover;
}

-(void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
    
    if(popoverController == self.reusablePopover) {  // Only on reusablePopover dismissal.
        
        switch(self.currentReusableView) {
                
            case FPKReusableViewNone: // This should never happens.
                break;
                
            case FPKReusableViewOutline:
            case FPKReusableViewBookmarks:
                
                self.currentReusableView = FPKReusableViewNone;
                break;
                
            case FPKReusableViewSearch:
                
                if(self.currentSearchViewMode == FPKSearchViewModeFull) {
                    
                    self.currentReusableView = FPKReusableViewNone;
                }
                break;
                
            default: break;
        }
    }
}

-(void)popoverPresentationControllerDidDismissPopover:(UIPopoverPresentationController *)popoverPresentationController
{
    switch(self.currentReusableView)
    {
            
        case FPKReusableViewNone: // This should never happens.
            break;
            
        case FPKReusableViewOutline:
        case FPKReusableViewBookmarks:
            
            // The popover has been already dismissed, just set the flag accordingly.
            
            self.currentReusableView = FPKReusableViewNone;
            break;
            
        case FPKReusableViewSearch:
            
            if(self.currentSearchViewMode == FPKSearchViewModeFull)
            {
                self.currentReusableView = FPKReusableViewNone;
            }
            break;
            // Same as above, but also cancel the search.
            
        default: break;
    }
}

-(void)dismissAlternateViewController {
    
    switch(self.currentReusableView) {
            
        case FPKReusableViewNone:
            break;
            
        case FPKReusableViewText:
            
            if(self.presentedViewController) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            
            self.currentReusableView = FPKReusableViewNone;
            
            break;
            
        case FPKReusableViewOutline:
        case FPKReusableViewBookmarks:
            
            // Same procedure for both outline and bookmark.
            
            if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
                
                if([UIPresentationController class])
                {
                    if(self.presentedViewController) {
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }
                }
                else
                {
                    [self.reusablePopover dismissPopoverAnimated:YES];
                }
                
            } else {
                
                /* On iPad iOS 8 and iPhone whe have a presented view controller */
                
                if(self.presentedViewController) {
                    [self dismissViewControllerAnimated:YES completion:nil];
                }
            }
            self.currentReusableView = FPKReusableViewNone;
            break;
            
        case FPKReusableViewSearch:
            
            if(self.currentSearchViewMode == FPKSearchViewModeFull) {
           
                [self dismissSearchViewController:_searchViewController];
                self.currentReusableView = FPKReusableViewNone;
                
            } else if (self.currentSearchViewMode == FPKSearchViewModeMini) {
           
                [self dismissMiniSearchView];
                self.currentReusableView = FPKReusableViewNone;
            }
            
            // Cancel search and remove the controller.
            
            break;
        default: break;
    }
}

-(void)presentViewController:(UIViewController *)controller
                    fromRect:(CGRect)rect
                  sourceView:(UIView *)view
                 contentSize:(CGSize)contentSize
{
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

        if([UIPopoverPresentationController class]) {
            
            if(self.presentedViewController) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            
            controller.modalPresentationStyle = UIModalPresentationPopover;
            controller.preferredContentSize = contentSize;
            
            [self presentViewController:controller animated:YES completion:nil];
            
            UIPopoverPresentationController * popoverPresentationController = controller.popoverPresentationController;
            popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
            popoverPresentationController.sourceRect = rect;
            popoverPresentationController.sourceView = view;
            popoverPresentationController.delegate = self;
            
        } else {
            
            [self prepareReusablePopoverControllerWithController:controller];
            
            [self.reusablePopover setPopoverContentSize:contentSize animated:YES];
            [self.reusablePopover presentPopoverFromRect:rect inView:view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
        
    } else {
        
        [self presentViewController:controller animated:YES completion:nil];
    }
}

-(void)presentViewController:(UIViewController *)controller
               barButtonItem:(UIBarButtonItem *)barButtonItem
                 contentSize:(CGSize)contentSize
{
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        if([UIPopoverPresentationController class]) {
                
            if(self.presentedViewController) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            
            controller.modalPresentationStyle = UIModalPresentationPopover;
            
            UIPopoverPresentationController * popoverPresentationController = controller.popoverPresentationController;
            
            popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
            popoverPresentationController.barButtonItem = barButtonItem;
            popoverPresentationController.delegate = self;
            
            [self presentViewController:controller animated:YES completion:nil];
        }
        else
        {
            [self prepareReusablePopoverControllerWithController:controller];
            
            [self.reusablePopover setPopoverContentSize:contentSize animated:YES];
            [self.reusablePopover presentPopoverFromBarButtonItem:barButtonItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
        }
    }
    else
    {
        [self presentViewController:controller animated:YES completion:nil];
    }
}

#pragma mark -
#pragma mark ThumbnailSlider

-(IBAction) actionThumbnail:(id)sender{
	
	if (self.thumbsViewVisible) {
		[self hideThumbnails];
	}else {
//        [self showThumbnails];
	}
}

#pragma mark -
#pragma mark TextDisplayViewController, _Delegate and _Actions

-(TextDisplayViewController *)textDisplayViewController {

	if(!_textDisplayViewController) {
		_textDisplayViewController = [[TextDisplayViewController alloc]initWithNibName:@"TextDisplayView" bundle:[NSBundle bundleForClass:[self class]]];
		_textDisplayViewController.documentManager = self.document;
	}
	
	return _textDisplayViewController;
}


#pragma mark - Status bar

-(UIStatusBarStyle)preferredStatusBarStyle {
    if(self.rollawayToolbar == nil || self.rollawayToolbar.hidden) {
        return UIStatusBarStyleDefault;
    }
    return UIStatusBarStyleLightContent;
}

#pragma mark - UIToolbarDelegate

-(UIBarPosition)positionForBar:(id<UIBarPositioning>)bar {
    if (bar == self.rollawayToolbar) {
        return UIBarPositionTopAttached;
    }
    return UIBarPositionAny;
}


#pragma mark -
#pragma mark OutlineViewController, _Delegate and _Actions

-(void)dismissOutlineViewController:(OutlineViewController *)anOutlineViewController {
	
    [self dismissAlternateViewController];
}

-(void)outlineViewController:(OutlineViewController *)ovc didRequestDestination:(id<FPKDestination>)destination file:(NSString *)file {
    
    if(file) {
        return;
    }
    
    [self setDestination:destination];
    [self dismissAlternateViewController];
}

-(OutlineViewController *)outlineViewController {
    
    if(!_outlineViewController) {
        _outlineViewController = [[OutlineViewController alloc]initWithNibName:@"OutlineView" bundle:[NSBundle bundleForClass:[self class]]];
        [_outlineViewController setOutlineEntries: [[self document] outline]];
        _outlineViewController.delegate = self;
    }
    return _outlineViewController;
}


#pragma mark - SearchViewControllerDelegate

-(MFDocumentManager *)documentForSearchViewController:(SearchViewController *)controller {
    return self.document;
}

-(SearchManager *)searchForSearchViewController:(SearchViewController *)controller {
    return [self searchManager];
}

-(void)searchViewController:(SearchViewController *)controller setPage:(NSUInteger)page withZoomOfLevel:(float)zoomLevel onRect:(CGRect)rect {
    [self setPage:page withZoomOfLevel:zoomLevel onRect:rect];

}

-(void)searchViewController:(SearchViewController *)controller addSearch:(SearchManager *)searchManager {
    
    [self addOverlayViewDataSource:searchManager name:@"FPKSearchManager"];
    [self reloadOverlay];
}

-(void)searchViewController:(SearchViewController *)controller removeSearch:(SearchManager *)searchManager {
    
    [self removeOverlayViewDataSourceWithName:@"FPKSearchManager"];
    [self reloadOverlay];
}

-(void)searchViewController:(SearchViewController *)controller switchToMiniSearchView:(FPKSearchMatchItem *)item {
    
    [self dismissSearchViewController:self.searchViewController];
    [self presentMiniSearchViewWithStartingItem:item];
}

-(NSUInteger)pageForSearchViewController:(SearchViewController *)controller {
    return self.page;
}

-(void)dismissSearchViewController:(SearchViewController *)aSearchViewController {
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        if([UIPopoverPresentationController class]) {
            if(self.presentedViewController) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
        else
        {
            [self.reusablePopover dismissPopoverAnimated:YES];
        }
    }
    else
    {
        /* Dismiss the presented view controller on iPad iOS 8 and iPhone */
        if(self.presentedViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
    
    self.currentReusableView = FPKReusableViewNone;
}

#pragma mark - Search stuff

-(void)revertToFullSearchView {
    
    [self dismissMiniSearchView];
    [self presentFullSearchView];
}

-(void)handleSearchGotCancelledNotification:(NSNotification *)notification {
    
    if(self.currentReusableView == FPKReusableViewSearch) {
        [self dismissSearchViewController:self.searchViewController];
    }
}

-(void)handleSearchUpdateNotification:(NSNotification *)notification {
    
    NSDictionary * userInfo = notification.userInfo;
    NSInteger page = [userInfo[kNotificationSearchInfoPage] integerValue];
    NSInteger delta = page - self.page;
    
    if(self.isViewLoaded && (delta < 2)) {
        [self reloadOverlay];
    }
}

-(void)presentFullSearchView {
	
    SearchViewController * controller = self.searchViewController;
    controller.delegate = self;
    controller.searchManager = [self searchManager];
    
    self.overlayEnabled = YES;
    
    self.currentReusableView = FPKReusableViewSearch;
    self.currentSearchViewMode = FPKSearchViewModeFull;
    
    CGSize popoverContentSize = CGSizeMake(450, 650);
    [self presentViewController:controller
                  barButtonItem:self.searchBarButtonItem
                    contentSize:popoverContentSize];
}

-(MiniSearchView *)miniSearchView {
    if(!_miniSearchView) {
        // If nil, allocate and initialize it.
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            
            MiniSearchView * view = [[MiniSearchView alloc]initWithFrame:CGRectMake(0, -45, self.view.bounds.size.width, 44)];
            view.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.75];
            [view setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleRightMargin];
            self.miniSearchView = view;
        } else {
            
            MiniSearchView * view = [[MiniSearchView alloc]initWithFrame:CGRectMake(0, -45, self.view.bounds.size.width, 44)];
            view.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.75];
            [view setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleRightMargin];
            self.miniSearchView = view;
        }
    }
    
    return _miniSearchView;
}

-(void)presentMiniSearchViewWithStartingItem:(FPKSearchMatchItem *)item {
	
    if(self.miniSearchView.superview != nil) {
        [self.miniSearchView removeFromSuperview];
    }
    
	// Set up the connections
    
	self.miniSearchView.delegate = self;
	
	// Update the view with the right index.
	[self.miniSearchView reloadData];
    self.miniSearchView.currentSearchResultIndex = [[[self searchManager] allSearchResults] indexOfObject:item];
	
	// Add the subview and referesh the superview.
	[[self view]addSubview:self.miniSearchView];
	
    [UIView animateWithDuration:0.25f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
                             
                             self.miniSearchView.frame = CGRectMake(0, (self.topLayoutGuide.length + self.rollawayToolbar.frame.size.height), self.view.bounds.size.width, 44);
                             self.miniSearchView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleRightMargin;
                             
                         } else {
                             
                             self.miniSearchView.frame = CGRectMake(0, (self.topLayoutGuide.length +  self.rollawayToolbar.frame.size.height), self.view.bounds.size.width, 44);
                             self.miniSearchView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleRightMargin;
                         }
                     }
                     completion:^(BOOL finished){
                         
                         [self.view bringSubviewToFront:self.rollawayToolbar];
                         
                         self.currentReusableView = FPKReusableViewSearch;
                         self.currentSearchViewMode = FPKSearchViewModeMini;
                     }];
}

-(SearchManager *)searchManager {
    id<FPKOverlayViewDataSource> dataSource = [self overlayViewDataSourceWithName:@"FPKSearchManager"];
    if([dataSource isKindOfClass:[SearchManager class]]) {
        return (SearchManager *)dataSource;
    }
    return nil;
}

/**
 * SearchViewController, lazily allocated.
 */
-(SearchViewController *)searchViewController {
	
	// Lazily allocation when required.
	
	if(!_searchViewController) {
		
		// We use different xib on iPhone and iPad.
        
		if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
			_searchViewController = [[SearchViewController alloc]initWithNibName:@"SearchView2_pad" bundle:[NSBundle bundleForClass:[self class]]];
		} else {
			_searchViewController = [[SearchViewController alloc]initWithNibName:@"SearchView2_phone" bundle:[NSBundle bundleForClass:[self class]]];
            
		}
	}
	return _searchViewController;
}

-(IBAction)actionSearch:(id)sender {
    
    if(self.currentReusableView!= FPKReusableViewSearch) {
        
        if(self.currentSearchViewMode == FPKSearchViewModeMini) {
            
            [self revertToFullSearchView];
        
        } else {
            
            [self presentFullSearchView];
        }
        
    } else {
        
        if(self.currentSearchViewMode == FPKSearchViewModeMini) {
            
            [self revertToFullSearchView];
            
        } else if (self.currentSearchViewMode == FPKSearchViewModeFull) {
            
            [self dismissAlternateViewController];    
            
        }
    }
}

#pragma mark - MiniSearchViewDelegate

-(NSUInteger )numberOfSearchResults:(MiniSearchView *)view {
    
    NSUInteger count = [[[self searchManager] allSearchResults] count];
    return count;
}

-(FPKSearchMatchItem *)miniSearchView:(MiniSearchView *)view searchResultAtIndex:(NSUInteger)index {
    
    
    return [[[self searchManager] allSearchResults] objectAtIndex:index];
}

-(void)miniSearchView:(MiniSearchView *)view
              setPage:(NSUInteger)page
            zoomLevel:(float)zoomLevel
                 rect:(CGRect)rect {
    
    [self setPage:page withZoomOfLevel:zoomLevel onRect:rect];
}

-(void)dismissMiniSearchView:(MiniSearchView *)view {
    
    [self dismissMiniSearchView];
}

-(void)revertToFullSearchViewFromMiniSearchView:(MiniSearchView *)view {
    
    // Dismiss the minimized view and present the full one.
    [self revertToFullSearchView];
}

-(void)cancelSearch:(MiniSearchView *)view {
    
    [self dismissMiniSearchView];
    
    [[self searchManager] stopSearch];
    [self removeOverlayViewDataSourceWithName:@"FPKSearchManager"];
    [self reloadOverlay];
}

-(void)dismissMiniSearchView {
    
	// Animation.
    ReaderViewController * __weak this = self;
    [UIView animateWithDuration:0.25f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
                             
                             this.miniSearchView.frame = CGRectMake(0,-45 , this.view.bounds.size.width, 44);
                         } else {
                             
                             this.miniSearchView.frame = CGRectMake(0,-45 , this.view.bounds.size.width, 44);
                         }
                     }
                     completion:^(BOOL finished){
                         
                         if(this.miniSearchView!=nil) {
                             
                             [this.miniSearchView removeFromSuperview];
                         }
                     }];
}

-(void)showMiniSearchView {
	
    ReaderViewController * __weak this = self;
    [UIView animateWithDuration:0.25f delay:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        
            this.miniSearchView.frame = CGRectMake(0,66 , this.view.bounds.size.width, 44);
            this.miniSearchView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
        
        }else {
            
            this.miniSearchView.frame = CGRectMake(0,66 , this.view.bounds.size.width, 44);
            this.miniSearchView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
        }
    } completion:NULL];
}

#pragma mark - Actions

-(IBAction) actionDismiss:(id)sender {
	self.pdfOpen = NO;
	
    [self dismissAlternateViewController];
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:YES];
	if(self.dismissBlock) {
        self.dismissBlock();
    } else {
        
        if ([self navigationController]) {
            
            [[self navigationController] popViewControllerAnimated:YES];
            
        } else if(self.presentingViewController) {
                [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

-(void)pageSliderCancel:(UISlider *)slider {
    [super pageSliderCancel:slider];
    
    [self updatePageNumberLabel];
}

-(void)pageSliderSlided:(UISlider *)slider {
    
    [super pageSliderSlided:slider];
    
    // Get the slider value.
    NSNumber *number = [NSNumber numberWithFloat:[slider value]];
    NSUInteger pageNumber = [number unsignedIntValue];
    
    // Update the label.
    
    [self updatePageNumberLabelWithPage:pageNumber];
}

-(void)actionChangeAutomode:(id)sender {
	
	BOOL automode = [self automodeOnRotation];
	if(automode) {
		[self setAutomodeOnRotation:NO];
	} else {
		[self setAutomodeOnRotation:YES];
	}
}
#pragma mark - tableViewDelegate

//tableview row num
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.thumbnailArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * detailCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];

    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 10, 80, 100)];
    if (self.thumbnailArray.count != 0) {
       self.imageView.image = self.thumbnailArray[indexPath.row];
    }
    if (self.page  == indexPath.row + 1) {
        self.imageView.layer.borderWidth = 3;
        self.imageView.layer.borderColor = [UIColor greenColor].CGColor;
         [self.thumbnailView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row  inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    self.imageView.backgroundColor = [UIColor whiteColor];
    detailCell.backgroundColor = [UIColor clearColor];
    [detailCell addSubview:self.imageView];
    detailCell.textLabel.text= [NSString stringWithFormat:@"%ld",(long)indexPath.row + 1];
    return detailCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self setPage:indexPath.row + 1];
    [self.thumbnailView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row  inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
}

#pragma mark -
#pragma mark MFDocumentViewControllerDelegate

-(void) documentViewController:(MFDocumentViewController *)dvc didGoToPage:(NSUInteger)page
{
    NSString * labelText = [self pageLabelString];
    self.pagelabel.text = labelText;
    [self setPage:page];
    [self.thumbnailView reloadData];
    [self.thumbnailView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:page - 1  inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
//    [self updatePageNumberLabel];
}
-(void)dismissTextDisplayViewController:(TextDisplayViewController *)controller
{
    
    [self dismissAlternateViewController];
}

-(void)presentTextDisplayViewControllerForPage:(NSUInteger)page {
    
    TextDisplayViewController * controller = nil;
    
    if(self.currentReusableView != FPKReusableViewNone) {
        
        [self dismissAlternateViewController];
    }
    
    controller = self.textDisplayViewController;
    controller.delegate = self;
    [controller updateWithTextOfPage:page];
    
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        controller.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    
    [self presentViewController:controller animated:YES completion:nil];
   
    self.currentReusableView = FPKReusableViewText;
}


-(void) documentViewController:(MFDocumentViewController *)dvc didReceiveTapOnPage:(NSUInteger)page atPoint:(CGPoint)point {
	
        //unused

}

-(void)documentViewController:(MFDocumentViewController *)dvc willFollowLinkToPage:(NSUInteger)page {
    self.willFollowLink = YES;
}

//点击 隐藏／显示 toolBar
-(void) documentViewController:(MFDocumentViewController *)dvc didReceiveTapAtPoint:(CGPoint)point {
    if(self.willFollowLink) {
        self.willFollowLink = NO;
        return;
    }
	if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)) {
		
		[self dismissAlternateViewController];
	}
	if(!self.waitingForTextInput) {
        
        if(!self.multimediaVisible){
		
            if(self.hudHidden) {
                
                [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
                [self.thumbnailView reloadData];
                [self.thumbnailView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self page] - 1  inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
               
                [self showToolbar];
                [self showThumbnaiView];
//                [self showThumbnails];
                self.thumbnailBackgroundColor =[UIColor redColor];
//                self.pagelabel.hidden = YES;
                if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
//                    self.borderview.hidden = NO;
                }else
                {
                    self.borderview.hidden = YES;
                }
                
                self.miniSearchView.hidden = NO;
			
                self.hudHidden = NO;
			
            } else {
			
                // Hide
                [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
			
                [self hideToolbar];
                [self hideThumbnaiView];
                [self hideThumbnails];
                self.pagelabel.hidden = NO;
                self.borderview.hidden = YES;
                self.miniSearchView.hidden = YES;
			
                self.hudHidden = YES;
            }
        }
        
	} else {
    
        self.waitingForTextInput = NO;
        [self presentTextDisplayViewControllerForPage:[self page]];
    }
}



-(BOOL)shouldAutorotate {
    return YES;
}

-(UIInterfaceOrientationMask)supportedInterfaceOrientations {

    return UIInterfaceOrientationMaskAll;
}

-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
